package com.hxgis.common.service.cimiss;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxgis.common.config.cimiss.CimissConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;

@Component
@Slf4j
public class CimissHttpRequest {

    @Autowired
    private CimissConfig cimissConfig;

    @Autowired
    private RestTemplate restTemplate;

    private String getRequestAddress(String code,String interfaceId,Map<String,String> params){
        StringBuffer paramsStr = new StringBuffer();
        paramsStr.append(cimissConfig.getApiAdress());
        paramsStr.append("?");
        paramsStr.append("userId="+cimissConfig.getUserName());
        paramsStr.append("&");
        paramsStr.append("pwd="+cimissConfig.getPassword());
        paramsStr.append("&");
        paramsStr.append("dataCode="+code);
        paramsStr.append("&");
        paramsStr.append("interfaceId="+interfaceId);
        paramsStr.append("&");
        params.forEach((key, value) -> {
            paramsStr.append(key+"="+value);
            paramsStr.append("&");
        });
        paramsStr.append("dataFormat=json");
        return paramsStr.toString();
    }

    /**
     * 发送请求 用feture实现
     * @param code datacode
     * @param interfaceId 接口id
     * @param params 封装的参数
     * @param strings 站点list集合
     * @param splitNum 需要按多少个拆分 比如总站点数 2000 splitNum=500 就会分成4个线程去拉数据
     * @return
     */
    public<T> List<T> request(String code, String interfaceId, Map<String,String> params, List<String> strings, Integer splitNum , Class<T> clazz){
        Long startTime = System.currentTimeMillis();

        List<String>[] lists = com.hxgis.common.utils.CollectionUtils.subArrays(strings, splitNum);
        ExecutorService executor = Executors.newFixedThreadPool(lists.length);


        List<Future<List<T>>> futures = new ArrayList<>();

        for (int i = 0; i < lists.length; i++) {
            int jj = i;
            futures.add(executor.submit(() -> getTsByThread(code, interfaceId, params, clazz, jj, lists, startTime)));
        }

        List<T> resultList = new CopyOnWriteArrayList<>();
        futures.stream().forEach(future ->{
            try {
                List<T> subList = future.get();
//                if (!CollectionUtils.isEmpty(subList)){
                resultList.addAll(subList);
//                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
        log.info("总调用cimiss用时:{},总数据量大小:{}",System.currentTimeMillis() - startTime,resultList.size());
        return resultList;
    }


    public <T> List<T> getTsByThread(String code, String interfaceId, Map<String, String> params, Class<T> clazz, Integer index, List<String>[] lists,  Long startTime) {
        //拼接url
        params.put("staids", com.hxgis.common.utils.CollectionUtils.join(lists[index], ","));
        String requestAddress = getRequestAddress(code, interfaceId, params);
        //返回值
        String result = null;
        try {
            result = restTemplate.getForObject(requestAddress,String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        if (result != null ){
            JSONObject jsonObj =  JSONObject.parseObject(result);
            String returnCode = jsonObj.getString("returnCode");
            if (Objects.equals(returnCode,"0")){
                String ds = jsonObj.getString("DS");
                List<T> list = JSON.parseArray(ds, clazz);
                log.info("单线程调用cimiss用时:{},总数据量大小:{}",System.currentTimeMillis() - startTime,list.size());
                return list;
            }else { //异常返回
                log.error("[CheckTimer] 资料代码为" + code + ",接口为" + interfaceId + "的请求出现了错误:" + jsonObj.getString("returnMessage"));
            }
        }
        return null;
    }

    public <T> List<T> getTs(String code, String interfaceId, Map<String, String> params, Class<T> clazz, Long startTime) {
        //拼接url
        String requestAddress = getRequestAddress(code, interfaceId, params);
        //返回值
        String result = null;
        try {
            result = restTemplate.getForObject(requestAddress,String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        if (result != null ){
            JSONObject jsonObj =  JSONObject.parseObject(result);
            String returnCode = jsonObj.getString("returnCode");
            if (Objects.equals(returnCode,"0")){
                String ds = jsonObj.getString("DS");
                List<T> list = JSON.parseArray(ds, clazz);
                log.info("单线程调用cimiss用时:{},总数据量大小:{}",System.currentTimeMillis() - startTime,list.size());
                return list;
            }else { //异常返回
                log.error("[CheckTimer] 资料代码为" + code + ",接口为" + interfaceId + "的请求出现了错误:" + jsonObj.getString("returnMessage"));
            }
        }
        return null;
    }


}
